package ru.jexp.rcp.supply.swtext;

import org.eclipse.core.databinding.observable.Realm;
import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.core.databinding.property.INativePropertyListener;
import org.eclipse.core.databinding.property.ISimplePropertyListener;
import org.eclipse.core.databinding.property.value.SimpleValueProperty;


public class LookupFieldValueProperty<ReturnedT, LookupT extends ILookup<ReturnedT>> extends SimpleValueProperty
{
	private Class<ReturnedT> valueType;

	public LookupFieldValueProperty(Class<ReturnedT> valueType)
	{
		this.valueType = valueType;
	}
	
	@Override
	public Object getValueType()
	{
		return valueType;
	}

	@Override
	public INativePropertyListener adaptListener(ISimplePropertyListener listener)
	{
		return new LookupFieldListener<ReturnedT, LookupT>(this, listener);
	}
	
	@Override
	public IObservableValue observe(Realm realm, Object source)
	{
		return new LookupFieldObservableValue<ReturnedT, LookupT>(super.observe(realm, source), source);
	}
	
	public ILookupFieldObservableValue observe(LookupField<ReturnedT, LookupT> source)
	{
		return (ILookupFieldObservableValue) super.observe(source);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected Object doGetValue(Object source)
	{
		LookupField<ReturnedT, LookupT> lookup = (LookupField<ReturnedT, LookupT>) source; 
		return lookup.getValue();
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void doSetValue(Object source, Object value)
	{
		LookupField<ReturnedT, LookupT> lookup = (LookupField<ReturnedT, LookupT>) source;
		lookup.setValue((ReturnedT) value);
	}

}
